<template>
  <div class="ent-card shadow-enterprise-md animate-fade-in">
    <div class="ent-card-header flex items-center justify-between">
      <div class="flex items-center">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2 text-primary-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
        </svg>
        <h2 class="text-lg font-medium text-gray-800 dark:text-gray-200">查询结果</h2>
      </div>
      <div class="flex space-x-2">
        <button 
          @click="copyResults" 
          class="ent-btn-ghost text-xs p-1.5"
          title="复制结果"
        >
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
          </svg>
        </button>
        <button 
          @click="downloadCSV" 
          class="ent-btn-ghost text-xs p-1.5"
          title="下载CSV"
        >
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
        </button>
      </div>
    </div>

    <div class="ent-card-body p-0">
      <!-- SQL 显示部分 -->
      <div class="border-b border-gray-200 dark:border-gray-700">
        <div class="flex items-center px-6 pt-4 pb-2">
          <button
            @click="toggleSqlVisible"
            class="ent-btn-ghost text-xs p-1 mr-2"
          >
            <svg v-if="!sqlVisible" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
            </svg>
            <svg v-else xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
            </svg>
          </button>
          <span class="text-sm font-medium text-gray-600 dark:text-gray-400">生成的SQL</span>
          <button 
            @click="copySql" 
            class="ent-btn-ghost text-xs p-1 ml-2"
            title="复制SQL"
          >
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
            </svg>
          </button>
        </div>
        
        <transition name="ent-fade">
          <div v-if="sqlVisible" class="bg-gray-50 dark:bg-gray-800/50 px-6 py-3 overflow-x-auto">
            <pre class="text-xs text-gray-800 dark:text-gray-300 font-mono whitespace-pre-wrap">{{ sql }}</pre>
          </div>
        </transition>
      </div>

      <!-- 表格数据结果 -->
      <div class="overflow-x-auto">
        <table v-if="loading" class="ent-table">
          <tr v-for="i in 3" :key="i" class="ent-table-row">
            <td v-for="j in 4" :key="j" class="ent-table-td animate-pulse">
              <div class="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24"></div>
            </td>
          </tr>
        </table>

        <table v-else-if="resultData.length > 0" class="ent-table">
          <thead class="ent-table-header">
            <tr>
              <th 
                v-for="header in headers" 
                :key="header" 
                class="ent-table-th"
              >
                {{ header }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr 
              v-for="(row, index) in resultData" 
              :key="index"
              class="ent-table-row"
            >
              <td 
                v-for="header in headers" 
                :key="`${index}-${header}`"
                class="ent-table-td"
              >
                {{ formatValue(row[header]) }}
              </td>
            </tr>
          </tbody>
        </table>

        <div v-else class="p-6 text-center text-gray-500">
          查询完成，但没有返回任何数据
        </div>

        <!-- 分页和结果摘要 -->
        <div v-if="resultData.length > 0" class="px-6 py-3 border-t border-gray-200 dark:border-gray-700 flex justify-between text-sm text-gray-500 dark:text-gray-400">
          <div>
            共 {{ resultData.length }} 条记录
          </div>
          <div>
            查询ID: {{ queryId }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'

export default {
  name: 'ResultDisplay',
  props: {
    result: {
      type: Object,
      required: true
    },
    sql: {
      type: String,
      default: ''
    },
    loading: {
      type: Boolean,
      default: false
    },
    queryId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const sqlVisible = ref(false)
    
    const toggleSqlVisible = () => {
      sqlVisible.value = !sqlVisible.value
    }
    
    const headers = computed(() => {
      if (!props.result || props.loading) return []
      return Object.keys(props.result).length > 0 ? Object.keys(props.result[0]) : []
    })
    
    const resultData = computed(() => {
      if (!props.result || props.loading) return []
      return props.result
    })
    
    const formatValue = (value) => {
      if (value === null || value === undefined) return '-'
      if (typeof value === 'boolean') return value ? '是' : '否'
      if (typeof value === 'number') {
        // 数字格式化
        if (Number.isInteger(value)) return value.toString()
        return value.toFixed(2)
      }
      return value
    }
    
    const copyResults = () => {
      if (!props.result) return
      
      try {
        // 转换为CSV格式
        const headerRow = headers.value.join(',')
        const dataRows = resultData.value.map(row => 
          headers.value.map(header => `"${row[header]}"`).join(',')
        ).join('\n')
        
        const csvContent = `${headerRow}\n${dataRows}`
        
        navigator.clipboard.writeText(csvContent)
        alert('已复制结果到剪贴板')
      } catch (error) {
        alert('复制失败')
      }
    }
    
    const copySql = () => {
      if (!props.sql) return
      
      try {
        navigator.clipboard.writeText(props.sql)
        alert('已复制SQL到剪贴板')
      } catch (error) {
        alert('复制失败')
      }
    }
    
    const downloadCSV = () => {
      if (!props.result) return
      
      try {
        // 转换为CSV格式
        const headerRow = headers.value.join(',')
        const dataRows = resultData.value.map(row => 
          headers.value.map(header => `"${row[header]}"`).join(',')
        ).join('\n')
        
        const csvContent = `${headerRow}\n${dataRows}`
        
        // 创建下载链接
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        
        link.setAttribute('href', url)
        link.setAttribute('download', `query-result-${props.queryId || Date.now()}.csv`)
        link.style.visibility = 'hidden'
        
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } catch (error) {
        alert('下载失败')
      }
    }
    
    return {
      sqlVisible,
      toggleSqlVisible,
      headers,
      resultData,
      formatValue,
      copyResults,
      copySql,
      downloadCSV
    }
  }
}
</script>
